package com.example.testappwidget.ui.activity

import android.app.Activity
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.IBinder
import android.view.Window
import android.widget.TextView
import com.example.testappwidget.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


/*
 *Author: chinadragon
 *Time: 2BATTERY_UNKONW24/3/3BATTERY_UNKONW
 *
 * android电量显示动画 安卓显示电量的小组件
 *     https://blog.51cto.com/u_16BATTERY_UNKONW99264/74656BATTERY_UNKONW9
 */
class NewBatteryInfoActivity : Activity() {

    companion object {
        const val BATTERY_UNKONW = -1
        const val ACTION_NewBatteryWidget =
            "com.example.testappwidget.widgetprovidert.NewBatteryWidget"
    }

    /** TextView 声明 */
    private lateinit var tvBatteryStatus: TextView
    private lateinit var tvBatteryLevel: TextView
    private lateinit var tvBatteryHealth: TextView
    private lateinit var tvBatteryTemperature: TextView
    private lateinit var tvBatteryVoltage: TextView
    private lateinit var tvBatteryTechnology: TextView

    //定义电池信息变量
    var currentBatteryPlugged = BATTERY_UNKONW
    var currentBatteryStatus = BATTERY_UNKONW
    var currentBatteryLevel = BATTERY_UNKONW
    var currentBatteryHealth = BATTERY_UNKONW
    var currentBatteryTemperature = BATTERY_UNKONW
    var currentBatteryVoltage = BATTERY_UNKONW
    var currentBatteryTechnology: String? = ""

    /** 定义好字符串以备使用 */
    var batteryStatus = "电池状态: "
    var batteryLevel = "电池电量: "
    var batteryHealth = "电池健康: "
    var batteryTemperature = "电池温度: "
    var batteryVoltage = "电池电压: "
    var batteryTechnology = "电池技术: "

    var batteryStatusCharging = "正在充电"
    var batteryStatusDischarging = "正在放电"
    var batteryStatusFull = "已充满"
    var batteryStatusNotCharging = "未在充电"
    var batteryStatusUnknown = "状态未知"

    var batteryPluggedAC = "(AC)"
    var batteryPluggedUSB = "(USB)"

    var batteryHealthCold = "过冷"
    var batteryHealthDead = "损坏"
    var batteryHealthGood = "良好"
    var batteryHealthOverheat = "过热"
    var batteryHealthOverVoltage = "过压"
    var batteryHealthUnknown = "未知"
    var batteryHealthUnspecifiedFailure = "未知的故障"

    /** 提示Service启动标志位 */
    var flag: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.newlayout)
        initView()
        initData()
    }

    private fun initView() {
        tvBatteryStatus = findViewById(R.id.tvBatteryStatus)
        tvBatteryLevel = findViewById(R.id.tvBatteryLevel)
        tvBatteryHealth = findViewById(R.id.tvBatteryHealth)
        tvBatteryTemperature = findViewById(R.id.tvBatteryTemperature)
        tvBatteryVoltage = findViewById(R.id.tvBatteryVoltage)
        tvBatteryTechnology = findViewById(R.id.tvBatteryTechnology)
    }

    private fun initData() {
        //提示service的标志位置为true
        flag = true
        /** 注册提示信息的intentFilter */
        val filter = IntentFilter()
        filter.addAction(ACTION_NewBatteryWidget)
        registerReceiver(infoReceiver, filter)

        /** 启动提示service */
        val startService = Intent(this, UpdateService::class.java)
        startService(startService)

    }

    /** 提示信息接收器 */
    var infoReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent == null) {
                return
            }
            setText()
        }
    }

    /**
     * 收到intent，就及时修改TextView信息，使得Activity显示时，电池信息也能动态显示
     */
    /** 及时动态修改Activity上文字信息的函数 */
    private fun setText() {
        var plugState = ""
        when (currentBatteryPlugged) {
            BATTERY_UNKONW -> {
                plugState = ""
            }

            1 -> {

                plugState = batteryPluggedAC
            }


            2 -> {

                plugState = batteryPluggedUSB
            }

            else -> {
                plugState = ""
            }

        }

        when (currentBatteryStatus) {

            1 -> {
                tvBatteryStatus.setText(batteryStatus + batteryStatusUnknown);

            }


            2 -> {
                tvBatteryStatus.setText(batteryStatus + batteryStatusCharging + plugState);
            }

            3 -> {
                tvBatteryStatus.setText(batteryStatus + batteryStatusDischarging);
            }

            4 -> {
                tvBatteryStatus.setText(batteryStatus + batteryStatusNotCharging);

            }

            5 -> {
                tvBatteryStatus.setText(batteryStatus + batteryStatusFull + plugState);

            }

            else -> {
                tvBatteryStatus.setText(batteryStatus + batteryStatusUnknown);
            }
        }

        tvBatteryLevel.setText("$batteryLevel$currentBatteryLevel%")

        when (currentBatteryHealth) {
            1 -> {
                tvBatteryHealth.setText(batteryHealth + batteryHealthUnknown);
            }

            2 -> {
                tvBatteryHealth.setText(batteryHealth + batteryHealthGood);

            }

            3 -> {
                tvBatteryHealth.setText(batteryHealth + batteryHealthOverheat);

            }

            4 -> {
                tvBatteryHealth.setText(batteryHealth + batteryHealthDead);
            }

            5 -> {
                tvBatteryHealth.setText(batteryHealth + batteryHealthOverVoltage);

            }

            6 -> {
                tvBatteryHealth.setText(batteryHealth + batteryHealthUnspecifiedFailure);

            }

            7 -> {
                tvBatteryHealth.setText(batteryHealth + batteryHealthCold);

            }

            else -> {
                tvBatteryHealth.setText(batteryHealth + batteryHealthUnknown);
            }
        }

        tvBatteryTemperature.setText(batteryTemperature + currentBatteryTemperature / 10f + "℃")
        tvBatteryVoltage.setText(batteryVoltage + currentBatteryVoltage + "mv")
        tvBatteryTechnology.setText(batteryTechnology + currentBatteryTechnology)
    }


    /** 提示信息变化的service，约每隔一秒，就发送intent，
     * 提醒activity更新电池信息，主要为了检测电池状态的变化，
     * 例如连上充电时，状态会从“未在充电”变为“正在充电”
     * 通过调用plugged方式，还能判断是AC方式充电还是USB方式充电
     */
     inner class UpdateService : Service() {

        private val batteryReceiver: BroadcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent == null) {
                    return
                }
                currentBatteryStatus = intent.getIntExtra("status", BATTERY_UNKONW)
                currentBatteryLevel = intent.getIntExtra("level", BATTERY_UNKONW)
                currentBatteryHealth = intent.getIntExtra("health", BATTERY_UNKONW)
                currentBatteryTemperature = intent.getIntExtra("temperature", BATTERY_UNKONW)
                currentBatteryVoltage = intent.getIntExtra("voltage", BATTERY_UNKONW)
                currentBatteryTechnology = intent.getStringExtra("technology")
                currentBatteryPlugged = intent.getIntExtra("plugged", BATTERY_UNKONW)
            }

        }

        override fun onCreate() {

        }

        override fun onBind(intent: Intent?): IBinder? {
            return null
        }

        override fun onRebind(intent: Intent?) {
            super.onRebind(intent)
        }

        override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
            //注册BroadcastReceiver
            registerReceiver(batteryReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
            GlobalScope.launch {
                withContext(Dispatchers.Unconfined) {
                    while (flag) {
                        val sendInfoToActivity = Intent()
                        sendInfoToActivity.action = ACTION_NewBatteryWidget
                        sendBroadcast(sendInfoToActivity)
                        delay(1000)
                    }
                }
            }

            return super.onStartCommand(intent, flags, startId)
        }

        override fun onUnbind(intent: Intent?): Boolean {
            return super.onUnbind(intent)
        }


    }


}